package tools

import (
	"context"
	"encoding/json"
	"fmt"

	"gitee.com/EagleMao/eino_n9e_tool/pkg/logger"
	"github.com/cloudwego/eino/components/tool"
	"github.com/cloudwego/eino/schema"
)

type ToolQueryHistoryEvents struct {
	backService *N9EService
}

func GetQueryHistoryEventTool(backService *N9EService) tool.InvokableTool {
	return &ToolQueryHistoryEvents{
		backService: backService,
	}
}

type HistoryEventParam struct {
	Etime *int64 `json:"etime,omitempty"`
	Limit *int64 `json:"limit,omitempty"`
	P     *int64 `json:"p,omitempty"`
	// 根据告警名称或者标签搜索
	Query *string `json:"query,omitempty"`
	Rid   *int64  `json:"rid,omitempty"`
	// 根据告警等级搜索
	Severity *int64 `json:"severity,omitempty"`
	Stime    *int64 `json:"stime,omitempty"`
}

func (t *ToolQueryHistoryEvents) Info(ctx context.Context) (*schema.ToolInfo, error) {
	toolInfo := &schema.ToolInfo{
		Name: "query_alert_history_events",
		Desc: "查询告警事件历史列表",
		ParamsOneOf: schema.NewParamsOneOfByParams(
			map[string]*schema.ParameterInfo{
				"etime": {
					Type:     schema.Integer,
					Desc:     "结束时间",
					Required: false,
				},
				"limit": {
					Type:     schema.Integer,
					Desc:     "分页大小",
					Required: false,
				},
				"p": {
					Type:     schema.Integer,
					Desc:     "页码",
					Required: false,
				},
				"query": {
					Type:     schema.String,
					Desc:     "根据告警名称或者标签搜索",
					Required: false,
				},
				"rid": {
					Type:     schema.Integer,
					Desc:     "规则ID",
					Required: false,
				},
				"severity": {
					Type:     schema.Integer,
					Desc:     "根据告警等级搜索",
					Required: false,
				},
				"stime": {
					Type:     schema.Integer,
					Desc:     "起始时间",
					Required: false,
				},
			},
		),
	}

	return toolInfo, nil
}

func (t *ToolQueryHistoryEvents) InvokableRun(_ context.Context, argumentsInJSON string, opts ...tool.Option) (string, error) {
	p := &HistoryEventParam{}
	logger.Info(fmt.Sprintf("当前查询参数: %v", argumentsInJSON))
	if err := json.Unmarshal([]byte(argumentsInJSON), p); err != nil {
		return "", err
	}
	resp, err := t.backService.GetHistoryEvent(*p)
	if err != nil {
		return "", err
	}

	res, err := json.Marshal(resp)

	if err != nil {
		logger.Info(fmt.Sprintf("%v 序列号失败 %v", resp, err))
		return "", err
	}

	return string(res), err
}
